<template>
  <div class="count-box">
    <button ref="decrease" @click="updateNum(+$refs.num.value-1)">-</button>
    <input ref="num" type="number" :value="value" @change="updateNum(+$event.target.value)"/>
    <button @click="updateNum(+$refs.num.value+1)">+</button>
  </div>
</template>

<script>
export default {
  name: 'CountBox',
  props: {
    value: {
      type: Number,
      default: 1
    }
  },
  methods: {
    updateNum (num) {
      if (isNaN(num) || num < 1) {
        this.$refs.num.value = this.value
        return
      }
      if (num <= 1) {
        num = 1
        this.$refs.decrease.disabled = true
      } else {
        this.$refs.decrease.disabled = false
      }
      this.$emit('input', num)
    }
  }
}
</script>

<style lang="less" scoped>
.count-box {
  display: flex;
  align-items: center;

  button {
    border: none;
    padding: 8px 10px;
    height: 30px;
  }

  input {
    border: none;
    width: 40px;
    height: 30px;
    text-align: center;
    background: #f3ecec;
    margin: 0 5px;
  }
}
</style>
